<template>
  <div>
    <hot-table
      ref="hotTable"
      :data="templateData"
      :settings="hotSettings"
      class="margin-top text-sm"
    ></hot-table>
    <div v-loading.fullscreen.lock="fullscreenLoading"></div>
  </div>
</template>

<script>
import { clone } from "@/utils/clone";
import { HotTable } from "@handsontable/vue";
import Handsontable from "handsontable";
import { ajax } from "@/store/yg/common/utils";
import axios from "axios";
import { m } from "@/store/yg/common/local";
import * as constant from "@/store/yg/common/constant";
import "handsontable/languages/zh-CN";
import "handsontable/dist/handsontable.full.css";
import { parseTime, getFindKey } from "@/utils";
import globalData from "@/utils/config";
// import { log } from "console";
export default {
  components: {
    HotTable
  },
  props: {
    verifyShow: {
      type: Object,
      default: function() {
        return {};
      }
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    templateName: {
      validator: function(value) {
        // 这个值必须匹配下列字符串中的一个
        return ["Amoeba"].indexOf(value) !== -1;
      }
    },
    Constatvariable: {
      type: Object,
      default: function() {
        return {};
      }
    },
    templateType: {
      type: String,
      default: "receivable"
    },
    templateOptUser: {
      type: String,
      default: ""
    },

    templateData: {
      type: Array,
      default: function(params) {
        return [];
      }
    },
    oldData: {
      type: Array,
      default: function(params) {
        return [];
      }
    },
    receveToPay: {
      type: Array,
      default: function(params) {
        return [{}];
      }
    },
    payToReceve: {
      type: Array,
      default: function(params) {
        return [{}];
      }
    },
    templateDelReceveIds: {
      type: Array,
      default: function(params) {
        return [];
      }
    },
    templateDelPayIds: {
      type: Array,
      default: function(params) {
        return [];
      }
    },
    templateOptions: {
      type: Object,
      default: function(params) {
        return {};
      }
    },
    department: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      autoHeight: "auto",
      fullscreenLoading: false,
      headerList2: [
        // "序号",
        "应付部门",
        "阿米巴科目",
        "费用名称",
        "RMB单价",
        "数量",
        "RMB总额",
        "原币单价",
        "原币总额",
        "币种",
        "结算人",
        "结算日期",
        "创建日期",
        "创建人",
        // "修改人",
        "结转",
        "备注"
        // "操作"
      ],
      headerList: [
        "序号",
        "应收部门",
        "阿米巴科目",
        "关联科目",
        "费用名称",
        "RMB单价",
        "数量",
        "RMB总额",
        "原币单价",
        "原币总额",
        "币种",
        "结算人",
        "结算日期",
        "创建日期",
        "创建人",
        // "修改人",
        "结转",
        "备注",
        "操作"
      ],
      columns1: [
        {
          data: "selectStatus",
          width: 40,
          type: "checkbox"
        },
        {
          data: "receiveDepartId", // 应收部门
          // width: 80,
          type: "autocomplete",
          source: this.templateOptions.userDeparOptions
        },
        {
          data: "amoebaSubjectId", //阿米巴科目
          // width: 80,
          readOnly: true,
          type: "autocomplete",
          source: this.templateOptions.amoebaSubjectOptions
        },
        {
          data: "settleAmoebaSubjectId", //关联科目
          // width: 80,
          type: "autocomplete",
          source: this.templateOptions.amoebaSubjectOptions
        },
        {
          data: "costId", // 费用名称
          // width: 80,
          type: "autocomplete",
          source: this.templateOptions.configPayNameOptions
        },

        {
          data: "unitPrice", //单价
          // width: 80,
          type: "numeric",
          readOnly: true,
          numericFormat: {
            pattern: "0.00"
          }
        },
        {
          data: "count", //数量
          // width: 60,
          type: "text"
        },

        {
          data: "money", // 总额
          type: "text",
          readOnly: true
          // width: 80
        },
        {
          data: "currencyUnitPrice", // 原币单价  currencyUnitPrice count
          // width: 80,
          type: "numeric",
          numericFormat: {
            pattern: "0.00"
          }
        },
        {
          data: "currencyTotalCost", //总额
          // width: 80,
          readOnly: true,
          type: "numeric",
          numericFormat: {
            pattern: "0.00"
          }
        },
        {
          data: "currency", // 币种
          // width: 60,
          type: "autocomplete",
          source: this.templateOptions.currencyOptions
        },
        {
          data: "settleManId", // 结算人
          // width: 80,
          type: "autocomplete",
          source: this.templateOptions.userOptions
        },
        {
          data: "costDate", // 结算日期
          // width: 100,
          type: "date",
          readOnly: true,
          dateFormat: "YYYY-MM-DD"
        },
        {
          data: "cdate", // 创建日期
          // width: 100,
          readOnly: true,
          type: "date",
          dateFormat: "YYYY-MM-DD"
        },
        {
          data: "cuser", // 创建人
          // width: 80,
          readOnly: true,
          type: "text"
        },
        // {
        //   data: "updator", //修改人
        //   readOnly: true,
        //   width: 80,
        //   type: "text"
        // },
        {
          data: "isCarryOver", //结转
          // width: 80,
          type: "autocomplete",
          readOnly: true,
          source: ["是", "否"]
        },
        {
          data: "remark", //备注
          // width: 200,
          type: "text"
        },
        {
          readOnly: true,
          // width: 100,
          renderer: this.coverRenderer
        }
      ],
      columns2: [
        // {
        //   data: "selectStatus",
        //   width: 40,
        //   type: "checkbox"
        // },
        {
          data: "payDepartId", // 应付部门
          // width: 80,
          type: "autocomplete",
          source: this.templateOptions.userDeparOptions
        },
        {
          data: "amoebaSubjectId", //阿米巴科目
          // width: 80,
          type: "autocomplete",
          source: this.templateOptions.amoebaSubjectOptions
        },
        {
          data: "costId", // 费用名称
          // width: 80,
          type: "autocomplete",
          source: this.templateOptions.configPayNameOptions
        },

        {
          data: "unitPrice", //单价
          // width: 80,
          readOnly: true,
          type: "numeric",
          numericFormat: {
            pattern: "0.00"
          }
        },
        {
          data: "count", //数量
          // width: 60,
          type: "text"
        },

        {
          data: "money", // 总额
          type: "text",
          readOnly: true
          // width: 80
        },
        {
          data: "currencyUnitPrice", // 单价
          // width: 80,
          type: "numeric",
          numericFormat: {
            pattern: "0.00"
          }
        },
        {
          data: "currencyTotalCost", //总额
          // width: 80,
          readOnly: true,
          type: "numeric",
          numericFormat: {
            pattern: "0.00"
          }
        },
        {
          data: "currency", // 币种
          // width: 60,
          type: "autocomplete",
          source: this.templateOptions.currencyOptions
        },
        {
          data: "settleManId", // 结算人
          // width: 80,
          type: "autocomplete",
          source: this.templateOptions.userOptions
        },
        {
          data: "costDate", // 结算日期
          // width: 100,
          readOnly: true,
          type: "date",
          dateFormat: "YYYY-MM-DD"
        },
        {
          data: "cdate", // 创建日期
          // width: 100,
          readOnly: true,
          type: "date",
          dateFormat: "YYYY-MM-DD"
        },
        {
          data: "cuser", // 创建人
          // width: 80,
          readOnly: true,
          type: "text"
        },
        // {
        //   data: "updator", //修改人
        //   readOnly: true,
        //   width: 80,
        //   type: "text"
        // },
        {
          data: "isCarryOver", //结转
          // width: 80,
          type: "autocomplete",
          readOnly: true,
          source: ["是", "否"]
        },
        {
          data: "remark", //备注
          // width: 200,
          type: "text"
        }
        // {
        //   readOnly: true,
        //   // width: 100,
        //   renderer: this.coverRenderer
        // }
      ],
      changeList: [],
      props: ["unitPrice", "count", "settleManId"],
      changeSettleManId: false,
      delIds: []
    };
  },
  watch: {
    templateData: {
      handler(val) {
        console.log("templateData :>> ", val);
        var length = this.templateData.length;
        if (length < 6) {
          this.autoHeight = "200px";
        } else {
          this.autoHeight = "auto";
        }
      },
      immediate: true,
      deep: true
    },
    oldData: {
      handler(val) {
        console.log("oldData :>> ", val);
        sessionStorage.setItem(
          this.templateType + "-" + this.department,
          JSON.stringify(this.oldData)
        );
      },
      deep: true,
      immediate: true
    },
    templateType: {
      handler(val) {
        const id =
          this.templateType === "receivable"
            ? "receiveDepartId"
            : "payDepartId";
        this.props.push(id);
      },
      immediate: true,
      deep: true
    }
  },
  computed: {
    hotSettings() {
      return {
        currentRowClassName: "currentRow", // 为选中行添加类名，可以更改样式
        currentColClassName: "currentCol", // 为选中列添加类名
        // rowHeaders: true, // 行表头
        // headerTooltips: true, // 鼠标划过头部时的提示文字
        stretchH: "all", // 所有列宽小于表宽时,填充满整个表 all（所有列填充）/last（最后一列）/none(不填充)
        licenseKey: globalData.licensekey,
        // 定义表结构
        colHeaders:
          this.templateType === "receivable"
            ? this.headerList
            : this.headerList2,
        width: "100%",
        height: this.autoHeight,
        columns:
          this.templateType === "receivable" ? this.columns1 : this.columns2,
        tableClassName: ["first-class-name", "second-class-name"],
        language: "zh-CN",
        contextMenu: ["row_above", "row_below", "remove_row", "alignment"], // 开启右键菜单
        cells: this.rowReadonly,
        beforeRemoveRow: (index, amount, physicalRows, source) => {
          const data = clone(this.templateData);
          for (const i of physicalRows) {
            if (data[i] && data[i].cuser !== this.templateOptUser) {
              return false;
            }
          }
          if (!this.verifyShow.deleteAmoeba) {
            return false;
          }
          console.log("this.templateType :>> ", this.templateType);
          if (this.templateType === "payable") {
            return false;
          }

          if (this.templateData.length === 1) {
            this.templateData.push({});
          }
          const ids = [];
          for (const i of physicalRows) {
            if (data[i].id) {
              ids.push(data[i].id);
            }
          }
          this.delIds = ids;
        },
        beforeChange: (changes, source) => {
          //数据改变时触发此方法 捕捉数据更改
          console.log("changes: ", changes); // row, prop, oldVal, newVal
          console.log("source: ", source); // op
          // currencyUnitPrice count  unitPrice
          if (source && "edit" == source) {
            const [row, prop, oldValue, newValue] = changes[0];
            // 判断余额 是否等于总额
            if (
              this.templateData[row].remain !==
                this.templateData[row].totalCost &&
              prop !== "selectStatus"
            ) {
              console.log("不可编辑 :>> ");
              this.$notify.error({
                position: "bottom-right",
                message: "更改失败，费用已销账"
              });
              changes.length = 0;
              return;
            }
            if (prop) {
              if (prop == "count" && oldValue != newValue) {
                // 修改数量
                if (this.templateData[row].unitPrice < 0 && newValue < 0) {
                  this.$notify.error({
                    position: "bottom-right",
                    message: "不能数量与单价两个都是负数"
                  });
                  changes.length = 0;
                  return;
                }

                this.changeCount(row, newValue);
              } else if (prop == "unitPrice" && oldValue != newValue) {
                // 修改单价
                if (this.templateData[row].count < 0 && newValue < 0) {
                  this.$notify.error({
                    position: "bottom-right",
                    message: "不能数量与单价两个都是负数"
                  });
                  changes.length = 0;
                  return;
                }
                this.changeUnitPrice(row, newValue);
              } else if (prop == "currencyUnitPrice" && oldValue != newValue) {
                // 修改单价
                if (this.templateData[row].count < 0 && newValue < 0) {
                  this.$notify.error({
                    position: "bottom-right",
                    message: "不能数量与原币单价两个都是负数"
                  });
                  changes.length = 0;
                  return;
                }
                this.changeCurrencyUnitPrice(row, newValue);
              }
            }
          }
        },
        afterChange: async (changes, source) => {
          //数据改变时触发此方法 捕捉数据更改
          // console.log("changes :>> ", changes);
          // 保存成功数据
          this.setTdClass();

          if (!changes) return;
          const [row, prop, oldValue, newValue] = changes[0];
          // console.log("row :>> ", row);

          // TODO

          if (oldValue != newValue && prop !== "selectStatus") {
            const oldData =
              JSON.parse(
                sessionStorage.getItem(
                  this.templateType + "-" + this.department
                )
              ) || this.oldData;

            const list =
              this.templateType === "receivable"
                ? this.columns1
                : this.columns2;
            const col = list.findIndex(x => x.data === prop);

            if (
              (oldData[row] &&
                oldData[row][prop] !== this.templateData[row][prop]) ||
              !oldData[row]
            ) {
              await this.removeTdClass(row);
              const target = this.changeList.findIndex(
                x => x.row === row && x.col === 0
              );
              if (target > -1) {
                this.changeList.splice(target, 1);
              }

              this.changeList.push({
                row: row,
                col: 0,
                status: "change"
              });

              this.changeList.push({
                row: row,
                col: col,
                status: "change"
              });

              // console.log("修改必填数据 :>> ", this.changeList);

              this.setTdClass();
            }

            // 存在旧值，并且修改后的值 等于旧值
            if (
              oldData[row] &&
              oldData[row][prop] === this.templateData[row][prop]
            ) {
              await this.removeTdClass(row);

              // 剔除坐标
              this.changeList.splice(
                this.changeList.indexOf(row + "," + col),
                1
              );
              for (const i in this.changeList) {
                if (this.changeList[i].row === row && this.changeList[i].col) {
                  this.changeList.splice(i, 1);
                }
              }
              this.setTdClass();
            }

            if (prop === "settleManId") {
              this.changeSettleManId = true;
            }

            // sessionStorage.setItem("changeList", this.changeList);
          }
        },
        /**
         * [一个或多个cell被选中后触发(每选中一个触发一次)]
         * @param  {[number]} row              [开始cell的行索引]
         * @param  {[number]} column           [开始cell的列索引]
         * @param  {[number]} row2             [结束cell的行索引]
         * @param  {[number]} column2          [结束cell的列索引]
         * @param  {[object]} preventScrolling [Object with value property where its value change will be observed]
         * @param  {[number]} selectionLayerLevel [被选中的层级]
         */
        afterSelection: (
          row,
          prop,
          row2,
          prop2,
          preventScrolling,
          selectionLayerLevel
        ) => {
          setTimeout(async () => {
            if (row !== this.rowIndex) {
              await this.checkRowInChange();
            }
            this.rowIndex = row;
          });
        },
        /**
         * [当前单元格不被选中后触发]
         */
        afterDeselect: () => {
          console.log("当前单元格不被选中后触发 :>> ", this.rowIndex);
          setTimeout(() => {
            this.checkRowInChange();
          });
        },
        /**
         * [一行或者多行移除后触发]
         * @param  {[number]} index        [起始行的可视索引]
         * @param  {[number]} amount       [删除行的数量]
         * @param  {[array]}  physicalRows [被删除行的数据组成的数组]
         * @param  {[string]} source       [触发的源]
         */
        afterRemoveRow: (index, amount, physicalRows, source) => {
          console.log("this.delIds :>> ", this.delIds);
          this.batchDeleteAmoebaSettlementCenter({ ids: this.delIds });
        }
      };
    }
  },
  methods: {
    changeCount(index, val) {
      const target = this.templateData[index];
      const totalCost = (target.unitPrice * 100 * val) / 100;
      this.$set(this.templateData[index], "money", totalCost.toFixed(2));
    },
    changeUnitPrice(index, val) {
      const target = this.templateData[index];
      const totalCost = (val * 100 * target.count) / 100;
      this.$set(this.templateData[index], "money", totalCost.toFixed(2));
    },
    changeCurrencyUnitPrice(index, val) {
      const target = this.templateData[index];
      const totalCost = (val * 100 * target.count) / 100;
      this.$set(
        this.templateData[index],
        "currencyTotalCost",
        totalCost.toFixed(2)
      );
      // this.$set(this.templateData[index], "remain", totalCost.toFixed(2));
    },
    async setTdClass() {
      for (const i of this.changeList) {
        const td = this.$refs.hotTable.$el.children[0].children[0].children[0]
          .children[0].children[0].children[2].children[i.row].children[i.col];
        switch (i.status) {
          case "change":
            td.classList.add("bg-yellow");
            break;
          case "success":
            td.classList.add("bg-green");
            break;
          case "error":
            td.classList.add("bg-red");
            break;
        }
      }
    },
    removeTdClass(row) {
      const list =
        this.templateType === "receivable" ? this.columns1 : this.columns2;
      for (let i = 0; i < list.length; i++) {
        const td = this.$refs.hotTable.$el.children[0].children[0].children[0]
          .children[0].children[0].children[2].children[row].children[i];
        td.classList.remove("bg-yellow", "bg-green", "bg-red");
      }
    },
    async checkRowInChange() {
      const a = this.changeList.filter(
        i => i.row === this.rowIndex && i.col !== 0
      );
      if (a.length > 0) {
        console.log("执行保存 :>> ");
        // 执行保存
        await this.saveRowInfo(this.rowIndex);
      }
    },
    // 保存单行数据
    async saveRowInfo(row) {
      const index = clone(row);
      const tableData = clone(this.templateData);
      for (const j of this.props) {
        if (j === "receiveDepartId") {
          if (!tableData[index][j] && !tableData[index].settleManId) return;
        } else if (j === "payDepartId") {
          if (!tableData[index][j] && !tableData[index].settleManId) return;
        } else if (j === "settleManId") {
          const id =
            this.templateType === "receivable"
              ? "receiveDepartId"
              : "payDepartId";
          if (!tableData[index][j] && !tableData[index][id]) return;
        } else if (j === "unitPrice") {
          if (!tableData[index][j] && !tableData[index].currencyUnitPrice)
            return;
        } else if (!tableData[index][j]) return;
      }

      console.log(
        "this.templateData[index].id :>> ",
        this.templateData[index].id
      );
      const d = clone(tableData[index]);

      d.amoebaSubjectId = d.settleAmoebaSubjectId;
      d.waybillId = this.Constatvariable.id;
      d.isAborad = this.isAborad;

      if (tableData.id) {
        d.id = this.templateData[index].id;
      }

      const params = this.sortData(d);
      const postData = {
        count: params.count,
        currency: params.currency,
        currencyUnitPrice: params.currencyUnitPrice,
        remark: params.remark,
        // unitPrice: params.unitPrice,
        waybillId: this.Constatvariable.id
      };
      // 存在费用名称 取费用名称
      if (params.costId) {
        postData.costId = params.costId;
      } else {
        postData.amoebaSubjectId = params.amoebaSubjectId;
        postData.settleAmoebaSubjectId = params.settleAmoebaSubjectId;
      }
      if (params.id) {
        postData.id = params.id;
        postData.receiveDepartId = params.receiveDepartId;
      } else {
        postData.settleManId = params.settleManId;
      }

      if (this.changeSettleManId && params.id) {
        postData.settleManId = params.settleManId;
      }
      // console.log("postData :>> ", postData);
      const { code, data, message } = await ajax(
        "saveAmoebaSettlementCenter",
        postData
      );
      const list = clone(this.changeList);
      if (code === 200) {
        this.removeTdClass(row);
        for (let i = list.length - 1; i >= 0; i--) {
          if (list[i].row == row) {
            list.splice(i, 1);
          }
        }
        list.push({
          row: index,
          col: 0,
          status: "success"
        });
        console.log("index :>> ", index);
        // this.templateData[index].id = data.finance_amoeba_settlement_center;
        if (data.id) {
          tableData[index] = data;
          if (data.receiveDepartId) {
            tableData[
              index
            ].receiveDepartId = this.templateOptions.userDeparMap[
              data.receiveDepartId
            ];
          }
          // if (data.payDepartId) {
          //   tableData[index].payDepartId = this.templateOptions.userDeparMap[
          //     data.payDepartId
          //   ];
          // }
          // 科目
          if (data.settleAmoebaSubjectId) {
            tableData[
              index
            ].settleAmoebaSubjectId = this.templateOptions.amoebaSubjectMap[
              data.settleAmoebaSubjectId
            ];
          }
          // 科目
          if (data.amoebaSubjectId) {
            tableData[
              index
            ].amoebaSubjectId = this.templateOptions.amoebaSubjectMap[
              data.amoebaSubjectId
            ];
          }
          // 创建人
          if (data.cuser) {
            tableData[index].cuser = this.templateOptions.userMap[data.cuser];
          }

          // 结算人
          if (data.settleManId) {
            tableData[index].settleManId = this.templateOptions.userMap[
              data.settleManId
            ];
          }
          // 修改人
          if (data.updator) {
            tableData[index].updator = this.templateOptions.userMap[
              data.updator
            ];
          }
          // 费用
          if (data.costId) {
            tableData[index].costId = this.templateOptions.payNameMap[
              data.costId
            ];
          }

          tableData[index].isCarryOver = data.isCarryOver === 1 ? "是" : "否";
        }

        this.$message.success("保存成功!");
        this.$emit("update:templateData", tableData);
        sessionStorage.setItem(
          this.templateType + "-" + this.department,
          JSON.stringify(tableData)
        );
        this.$refs.hotTable.hotInstance.loadData(this.templateData);
      } else {
        list.push({
          row: index,
          col: 0,
          status: "error"
        });
        this.$message.error(message ? message : "保存失败");
      }
      this.changeList = list;
      // setTimeout(() => {
      //   this.setTdClass();
      // }, 1000);
    },
    sortData(data) {
      const j = clone(data);
      if (j.receiveDepartId) {
        j.receiveDepartId = Number(
          getFindKey(j.receiveDepartId, this.templateOptions.userDeparMap)
        );
      }
      if (j.payDepartId) {
        j.payDepartId = Number(
          getFindKey(j.payDepartId, this.templateOptions.userDeparMap)
        );
      }
      // 科目
      if (j.settleAmoebaSubjectId) {
        j.settleAmoebaSubjectId = Number(
          getFindKey(
            j.settleAmoebaSubjectId,
            this.templateOptions.amoebaSubjectMap
          )
        );
      }
      // 科目
      if (j.amoebaSubjectId) {
        j.amoebaSubjectId = Number(
          getFindKey(j.amoebaSubjectId, this.templateOptions.amoebaSubjectMap)
        );
      }
      // 创建人
      if (j.cuser) {
        j.cuser = Number(getFindKey(j.cuser, this.templateOptions.userMap));
      }

      // 结算人
      if (j.settleManId) {
        j.settleManId = Number(
          getFindKey(j.settleManId, this.templateOptions.userMap)
        );
      }
      // 修改人
      if (j.updator) {
        j.updator = Number(getFindKey(j.updator, this.templateOptions.userMap));
      }
      // 费用
      if (j.costId) {
        j.costId = Number(
          getFindKey(j.costId, this.templateOptions.payNameMap)
        );
      }

      if (j.count || j.count == 0) {
        j.count = Number(j.count);
      }
      if (j.unitPrice || j.unitPrice == 0) {
        j.unitPrice = Number(j.unitPrice);
      }
      if (j.currencyUnitPrice || j.currencyUnitPrice == 0) {
        j.currencyUnitPrice = Number(j.currencyUnitPrice);
      }
      if (j.currencyTotalCost || j.currencyTotalCost == 0) {
        j.currencyTotalCost = Number(j.currencyTotalCost);
      }
      // 转结
      j.isCarryOver = j.isCarryOver === "是" ? 1 : 0;
      return j;
    },
    //行只读
    rowReadonly(row, col, prop) {
      var cellProperties = {};

      if (this.templateType !== "receivable") {
        cellProperties.readOnly = true;
      } else if (
        this.templateData[row] &&
        this.templateData[row].cuser === "admin"
      ) {
        cellProperties.readOnly = true;
      } else if (
        this.templateData[row] &&
        this.templateData[row].amoebaSubjectId === "对外销售"
      ) {
        cellProperties.readOnly = true;
      }

      if (!this.verifyShow.editAmoeba) {
        cellProperties.readOnly = true;
      }

      return cellProperties;
    },
    coverRenderer(instance, td, row, col, prop, value, cellProperties) {
      td.innerHTML = ``; // 清空单元格子集

      // if (this.templateName === "Amoeba") {
      if (this.templateType === "receivable") {
        let btnCopy = document.createElement("i");
        let btn2 = document.createElement("i");
        btnCopy.onclick = params => {
          this.onCopy(row);
        };
        btnCopy.setAttribute(
          "class",
          "el-icon-circle-plus-outline margin-right-sm text-green"
        );

        // btn.textContent = value ? value : "默认";
        if (this.verifyShow.createAmoeba) {
          td.appendChild(btnCopy); //添加按钮到单元格
        }

        let btnDel = document.createElement("i");
        btnDel.setAttribute(
          "class",
          "el-icon-remove-outline margin-right-sm text-red"
        );

        btnDel.onclick = params => {
          console.log("this :>> ", this);
          this.onDel(row);
        };
        if (
          this.verifyShow.deleteAmoeba &&
          this.templateData[row].amoebaSubjectId !== "对外销售"
        ) {
          td.appendChild(btnDel); //添加按钮到单元格
        }

        // ------------------- 复制到应收 start ----------
        let btnToReceivable = document.createElement("i");
        btnToReceivable.setAttribute(
          "class",
          "el-icon-top margin-right-sm text-blue"
        );
        btnToReceivable.onclick = params => {
          this.copyToReceivable(row);
        };
        if (this.verifyShow.editAmoeba) {
          td.appendChild(btnToReceivable); //添加按钮到单元格
        }

        // ---------------------end-------------------------
      }
      return td;
    },
    copyToReceivable(row) {
      this.$confirm("确认保存并同步到应收？")
        .then(_ => {
          const target = clone(this.templateData[row]);
          if (this.checkRule(target)) {
            this.fullscreenLoading = true;
            const params = {
              ids: []
            };
            params.ids.push(target.id);

            console.log("当前的复制的应付数据");
            ajax("synAmoebaSettlementCenterToReceive", params).then(
              res => {
                this.fullscreenLoading = false;
                if (res.code == 200) {
                  // TODO 公司名等于当前客户
                  this.$message.success("保存成功!");
                  // TODO 保存操作 更新数据
                  this.$emit("updateToReceive");
                } else {
                  if (null != res.message) {
                    this.$message.error(m(res.message));
                  } else {
                    this.$message.error("系统错误,同步失败!");
                  }
                }
              },
              error => {
                console.log(error);
              }
            );
          }
        })
        .catch(_ => {});
    },
    onDel(row) {
      if (this.templateData.length > 0) {
        const data = this.templateData[row];
        if (this.templateType === "receivable") {
          if (null != data && null != data["id"]) {
            var ids = [];
            ids.push(data["id"]);
            var param = {};
            param["ids"] = ids;
            this.batchDeleteAmoebaSettlementCenter(param, "receivable", row);
          } else {
            //id 不存在 说明是在页面新加 不需要走后台
            console.info("id 不存在 说明是在页面新加 不需要走后台");
            this.templateData.splice(row, 1);
          }
        } else if (this.templateType === "payable") {
          if (null != data && null != data["id"]) {
            var ids = [];
            ids.push(data["id"]);
            var param = {};
            param["ids"] = ids;
            this.batchDeleteAmoebaSettlementCenter(param, "payable", row);
          } else {
            //id 不存在 说明是在页面新加 不需要走后台
            this.templateData.splice(row, 1);
            console.info("id 不存在 说明是在页面新加 不需要走后台");
          }
        }
      }
    },

    batchDeleteAmoebaSettlementCenter(param, type, row) {
      this.fullscreenLoading = true;
      ajax("batchDeleteAmoebaSettlementCenter", param).then(
        res => {
          this.fullscreenLoading = false;
          if (res.code == 200) {
            if (row) {
              // this.templateDelReceveIds.push(data["id"]);
              this.templateData.splice(row, 1);
            }
            this.delIds = [];
            this.$message.success("删除成功!");
          } else {
            if (null != res.message) {
              this.$message.error(m(res.message));
            } else {
              this.$message.error("系统错误,删除失败!");
            }
          }
        },
        error => {
          console.log(error);
        }
      );
    },

    onCopy(row) {
      const data = this.templateData[row];
      const params = {
        receiveDepartId: "",
        settleAmoebaSubjectId: data.settleAmoebaSubjectId,
        settleManId: this.templateOptions.userMap[
          this.Constatvariable.salesmanId
        ],
        costId: data.costId,
        amoebaSubjectId: data.amoebaSubjectId,
        unitPrice: data.unitPrice,
        money: data.money,
        currencyUnitPrice: data.currencyUnitPrice,
        cuser: this.templateOptUser,
        count: data.count,
        currency: data.currency,
        currencyTotalCost: data.currencyTotalCost,
        costDate: "",
        cdate: parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}"),
        isCarryOver: data.isCarryOver,
        amoebaSubjectId: "",
        accountDate: parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}"),
        remark: ""
      };

      this.templateData.splice(row + 1, 0, params);
      this.saveRowInfo(row + 1);
    },

    saveAmoebaSettlementCenter(row) {
      const target = clone(this.templateData[row]);
      if (this.checkRule(target)) {
        this.fullscreenLoading = true;
        var list = [];
        list.push(target);
        ajax("batchSaveAmoebaSettlementCenter", list).then(
          res => {
            this.fullscreenLoading = false;
            if (res.code == 200) {
              target.cuser = this.templateOptUser;
              target.accountDate = target.cdate = new Date().toLocaleDateString();
              // TODO 公司名等于当前客户
              this.payToReceve.push(target);
              // TODO 保存操作 更新数据
              this.$message.success("保存成功!");
            } else {
              if (null != res.message) {
                this.$message.error(m(res.message));
              } else {
                this.$message.error("系统错误,保存失败!");
              }
            }
          },
          error => {
            console.log(error);
          }
        );
      }
    },

    checkRule(i) {
      if (!i.receiveDepartId) {
        this.$message.error("请填写部门");
        return false;
      } else if (!i.costId) {
        this.$message.error("请填写费用名称");
        return false;
      } else if (i.count !== 0 && !i.count) {
        this.$message.error("请填写数量");
        return false;
      } else if (!i.currency) {
        this.$message.error("请填写币种");
        return false;
      } else if (i.unitPrice !== 0 && !i.unitPrice) {
        this.$message.error("请填写单价");
        return false;
      }

      return true;
    }
  }
};
</script>

<style></style>
